<?php

namespace App\Third\Service\Lsy;


use App\Common\Service\BaseService;
use App\Third\Model\ShopLsyGoodsStockModel;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;

class LsyShopGoodsStockService extends BaseService
{
    /**
     * 获取平台商品库存信息
     * @param array $where
     * @param array $field
     * @return array|\Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|null|object
     */
    public static function getGoodsStockInfo(array $where, array $field = ['*'])
    {
        return ShopLsyGoodsStockModel::query()->where($where)->select($field)->first() ?? [];
    }

    /**
     * 清空表，重置自增id
     * @author liu
     * @date 2021-02-02 17:06
     */
    public function truncate(){
        ShopLsyGoodsStockModel::query()->truncate();
    }

    /**
     * 写入数据 多数据
     * @param array $data
     * @param bool $mult
     * @return bool|\Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model
     * @author 1iu
     * @date 2021-02-02 17:20
     */
    public function insert(array $data, $mult = false){
        if ($mult) return ShopLsyGoodsStockModel::query()->insert($data);
        return ShopLsyGoodsStockModel::query()->create($data);
    }


    /**
     * 原生sql 入库
     * @author 1iu
     * @date 2021-02-03 14:04
     */
    public function insertFromSql(){
        $container = $this->container;
        $redis = $this->buildRedis;
        $stockm = $container->get(ShopLsyGoodsStockModel::class);
        //$table = config('databases.' . $stockm->getConnectionName() . '.database') . '.' . $stockm->getTable();
        $connection = $stockm->getConnectionName();
        $table = $stockm->getTable();
        $columns = '`itemId`,`createShopId`,`surplusQuantity`';
        $db = Db::connection($connection)->getPdo();
        try {
            $db->exec("truncate `{$table}`");
            $iterator = null;
            $data = [];
            while (false !== ($keys = $redis->scan($iterator, "lsy:*:stock"))) {
                foreach ($keys as $v) {
                    $lsy_shop_no = explode(':', $v)[1];
                    foreach ($redis->hGetAll($v) as $crm_goods_id => $stock) {
                        $data[] = "('{$crm_goods_id}',{$lsy_shop_no},{$stock})";
                    }
                }
            }
            $parameters = implode(',', $data);
            $sql = "insert into {$table} ({$columns}) values {$parameters}";
            $db->exec($sql);//不记录sql
            //Db::connection('statistics')->select($sql);
        }catch (\Exception $e){
            $container->get(LoggerFactory::class)
                ->get('库存入库异常','LsyShopGoodsStockTask')
                ->error("库存缓存入库异常", ['error' => $e->getMessage()]);
        }

    }

    /**
     * 使用pdo 写入大量数据
     * 需配置 'options' => [PDO::MYSQL_ATTR_LOCAL_INFILE => true],
     * @param string $path
     * @return bool
     * @author liu
     * @date 2021-02-03 13:40
     */
    public function insertFromLocalFile(string $path){
        $container = $this->container;
        try {
//            $redis = $this->buildRedis;
//            $iterator = null;
//            $data = [];
//            while(false !== ($keys = $redis->scan($iterator,"lsy:*:stock"))) {
//                foreach($keys as $v) {
//                    $lsy_shop_no = explode(':', $v)[1];
//                    foreach ($redis->hGetAll($v) as $crm_goods_id => $stock){
//                        $data[] = "{$crm_goods_id},{$lsy_shop_no},{$stock}";
//                    }
//                }
//            }
//            $parameters = implode("\n", $data);
//            $path = BASE_PATH . '/runtime/stock.sql';
//            file_put_contents($path, $parameters);
            $stockm = $container->get(ShopLsyGoodsStockModel::class);
            $connection = $stockm->getConnectionName();
            $table = $stockm->getTable();
            $columns = '`itemId`,`createShopId`,`surplusQuantity`';
            $load = "LOAD DATA LOCAL INFILE '{$path}' INTO TABLE {$table} FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' ({$columns})";
            Db::connection($connection)->getPdo()->exec($load);
        }catch (\Exception $e){
            $container->get(LoggerFactory::class)
                ->get('库存入库异常','LsyShopGoodsStockTask')
                ->error("库存缓存入库异常", ['error' => $e->getMessage()]);
        }
    }
}
